<?php

namespace app\service;


use app\model\TaskModel;

class WorkbenchUserService
{

    public function __construct()
    {
    }

    /**
     * 统计任务同属
     * @param $userIds
     * @param $startTime
     * @param $endTime
     * @param $timeType
     * @param $projectId
     * @return array
     */
    public function taskCount($userIds, $startTime, $endTime, $timeType, $projectId): array
    {
        $query = (new TaskModel)->field('count(*) as number');
        $query = $this->taskCountWhere($query, $userIds, $startTime, $endTime, $timeType, $projectId);
        $query = $query->find();
        if (empty($query->toArray())) {
            return [];
        }
        $data = $query->toArray();
        return [
            [
                'number' => intval($data['number']),
                'end_time' => date('Y-m-d', $endTime)
            ]
        ];
    }

    /**
     * @param $query
     * @param $userIds
     * @param $startTime
     * @param $endTime
     * @param $timeType
     * @param $projectId
     * @return mixed
     */
    public function taskCountWhere($query, $userIds, $startTime, $endTime, $timeType, $projectId)
    {
        if (!empty($userIds)) {
            $query->join('task_member', 'task_member.task_id = task.id')->whereIn('task_member.partner', $userIds);
        }
        if ($timeType == 'plan_end_time') {
            if (!empty($startTime)) {
                $query->whereFieldRaw('task.plan_end_time', '>=', $startTime);
            }
            if (!empty($endTime)) {
                $query->whereFieldRaw('task.plan_end_time', '<=', $endTime);
            }
        }
        if ($timeType == 'end_time') {
            if (!empty($startTime)) {
                $query->whereFieldRaw('task.end_time', '>=', $startTime);
            }
            if (!empty($endTime)) {
                $query->whereFieldRaw('task.end_time', '<=', $endTime);
            }
        }
        if (!empty($projectId)) {
            $query->where('task.project_id', $projectId);
        }
        $closedId = StatusService::getInstance()->byCode('closed')['id'];
        $query->whereFieldRaw('task.step_type', '<>', TaskModel::STEP_TYPE_STEP_CATEGORY);
        $query->whereFieldRaw("get_json_string(task.`json`,'task_status')", '<>', $closedId);
        return $query;
    }

}
